/**
 * Created by aifece on 15/2/5.
 */
;(function(){
  // 地址
  function AddressCurr(option)
  {
    AddressJs.call(this, option);
  }

  for (var i in AddressJs.prototype) {
    AddressCurr.prototype[i] = AddressJs.prototype[i]
  }

  AddressCurr.prototype.setForm = function(obj) {
    var type = obj.data('type');
    var id = obj.attr('data-address_id');

    if (type == 'child') {
      obj.closest('li').addClass('pen-curr').siblings('li').removeClass('pen-curr');
      $('.js_addressFormDiv').show();
    } else if (id == 'new') {
      $('.js_addressFormDiv').show();
      this.sltChange(obj);
    } else {
      $('.js_addressFormDiv').hide();
      this.sltChange(obj);
    }

    if (id == 'new') {
      this.showInfo(0, 'new');
    } else {
      this.showInfo(id, 'edit');
    }
  }

  AddressCurr.prototype.sltChange = function(obj)
  {
    obj.siblings('li').removeClass('pen-curr');
    obj.addClass('pen-curr');
  }

  // 提示信息
  AddressCurr.prototype.inputMsg =  function(obj, msg) {
    obj.closest('label').addClass('crr');
    obj.closest('label').append('<a href="javascript:void(0);"><em><img src="'+siteUrl+'/images/flase-icon.png"/></em>'+msg+'</a>');
  }

  AddressCurr.prototype.deleteMsg = function(obj){
    obj.closest('label').removeClass('crr');
    obj.closest('label').find('a').remove();
  }

  AddressCurr.prototype.setInfo = function(type, id, info, receiver, address, mobile, provT, cityT, distT)
  {
    if (!id) {
      return;
    }
    var _this = this;

    if (type == 'new') {
      $(_this.option.listDiv).find('li').removeClass('pen-curr');
      $(_this.option.listDiv).prepend('<li data-address_id="'+id+'" class="js_addressEdit pen-curr"><em class="ico"></em>' + info + '<span data-type="child" data-address_id="'+id+'">编辑</span></li>');
    } else {
      $(_this.option.listDiv).find('li').each(function() {
        if ($(this).attr('data-address_id') == id) {
          $(this).html('<em class="ico"></em>' + info+'<span data-type="child" data-address_id="'+id+'">编辑</span>');
          _this.sltChange($(this));
        }
      });
    }

    $('.js_addressInfo').attr('data-address_id', id);

    $('.js_addInfoReceiver').val(receiver);
    if (!mobile) {
      mobile = tel;
    }
    $('.js_addInfoMobile').val(mobile);
    $('.js_addInfoAddress').val(address);
    $('.js_addInfoProvince').val(provT);
    $('.js_addInfoCity').val(cityT);
    $('.js_addInfoDistrict').val(distT);
  }

  $(function(){
    new AddressCurr();

    // 设为默认
    $('.js_ADDIsDefault').on('click', function(){
      var isDef = $(this).hasClass('skin-check');
      if (isDef) {
        $(this).removeClass('skin-check');
      } else {
        $(this).addClass('skin-check');
      }
    });

  // 批量上传图片
  setTimeout(function(){  // 阻止崩溃
    $('#js_fileUpload').uploadify({
      'swf'        : siteUrl+'/js/uploadify/uploadify.swf',
      'uploader'   : siteUrl+'/core/handler/file_uploader/uploadify',
      'queueID'    : 'queue',
      'width'      : '62',
      'height'     : '62',
      'buttonText' : '',
      'dataType'   : 'json',
      'onUploadStart': function (fileObj) {
        var fileName = fileObj.name;
        if ($('div[data-name="'+ fileName +'"]').length > 0) {
          //showMsg("已存在名为:" + fileName + "的文件，请重新选择文件！");
          this.cancelUpload(fileObj.id);
        }
      },
      'onUploadSuccess': function(error, content)  {
        var image = $.parseJSON(content);
        var imgPath = image.small;
        var fileId  = image.id;
        var fileName = image.file_name;
        var img = '<img src="' + imgPath + '" />';
        
        var ids = $('.js_serviceImg').val();
        if (ids.length == 0) {
          $('.js_serviceImg').val(fileId);
        } else {
          $('.js_serviceImg').val(ids+','+fileId);
        }

        $('.js_imageInput').before('<div data-name="'+ fileName +'" data-id="'+fileId+'" class="image-chunk"><div class="close js_deleteImg"></div>'+img+'<div class="progress js_fileProgress"></div></div>');
      },
      'onError' : function (event, ID, fileObj, errorObj) {
        if (errorObj.type === "File Size"){
          showMsg('超过文件上传大小限制（2M）！');
          return;
        }
        showMsg(errorObj.type + ', Error: ' + errorObj.info);
      }
    });
  }, 10);
/*
    // 图片上传
    $('#js_fileUpload').fileupload({
      dataType: 'json',
      autoUpload: true,
      //acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
      maxFileSize: 5000000,
      done : function(e, data){
        var ids = $('.js_serviceImg').val();
        if (ids.length == 0) {
          $('.js_serviceImg').val(data.result.id);
        } else {
          $('.js_serviceImg').val(ids+','+data.result.id);
        }

        $('div[data-name="'+ data.result.file_name +'"]').attr('data-id', data.result.id);
      },
      progressall:function(e, data){
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('.js_fileProgress').each(function(){
          var size = $(this).data('size');
          var progress = parseInt(data.loaded / size * 100, 10);
          $(this).css({ width:progress+'%' });
        });
        if (progress == 100) {
          $('.js_fileProgress').css({ width:'0px' }).removeClass('js_fileProgress');
        }
      }
    }).on('fileuploadadd', function (e, data) {
      var _this = $(this);
      $.each(data.files, function (index, file) {
        viewImage(file);
      });
    });
*/
    // 删除已上传图片
    $('.js_imageDiv').on('click', '.js_deleteImg', function(){
      var id = $(this).parent().attr('data-id');
      if (id) {
        var ids = $('.js_serviceImg').val().split(',');
        var newIds = new Array();
        if (ids.length > 0) {
          for (var i = 0; i < ids.length; i++) {
            if (ids[i] != id) {
              newIds.push(ids[i]);
            }
          }
          $('.js_serviceImg').val(newIds.join(','));
        }
      }
      $(this).parent().remove();
    });

    // 选择服务类型
    $('.js_sltService li').on('click', function(){
      var type = $(this).data('type');
      if ($(this).hasClass('who-curr')) {
        $(this).removeClass('who-curr').siblings().removeClass('who-curr');
        type = 0;
        $('.js_serviceFormDiv').addClass('hidden');
      } else {
        $(this).addClass('who-curr').siblings().removeClass('who-curr');
        $('.js_serviceFormDiv').removeClass('hidden');
        initForm(type);
      }
      if (type == 1) {
        $('.js_orderGoodsList').find('li').each(function(){
          var maxNum = $(this).attr('data-max_num');
          $(this).attr('data-curr_num', maxNum);
          $(this).find('.js_sltGoods').css({ visibility:'hidden' });
          $(this).find('.js_goodsViewNumber').css({ visibility:'hidden' });
          $(this).find('.js_numberInp').val(maxNum);
        });
        $('.back-check').addClass('back-label').removeClass('back-check');
      } else {
        $(this).attr('data-curr_num', 1);
        $('.js_sltGoods').css({ visibility:'visible' });
        $('.js_goodsViewNumber').css({ visibility:'visible' });
        $('.js_numberInp').val(1);
        $('.back-label').addClass('back-check').removeClass('back-label');
      }
      $('.js_sltService').attr('data-service_type', type);
    });

    // 选择商品
    $('.js_sltGoods').on('click', function(){
      if ($(this).closest('li').find('.disabled').length > 0) {
        return false;
      }
      var currSpan   = $(this).children('span');
      var currStatus = currSpan.hasClass('back-check'); // 为选中
      var status = $('.js_orderGoodsList').attr('data-disabled');
      if (currStatus && status != 1) {
        currSpan.removeClass('back-check');
        currSpan.addClass('back-label');
        currSpan.css({ marginRight:'9px' });
      } else {
        currSpan.addClass('back-check');
        currSpan.removeClass('back-label');
        currSpan.css({ marginRight:'10px' });
      }

      return false;
    });

    //+-
    $('.js_subNum').on('click', function(){
      var currNum = $(this).closest('li').find('.js_numberInp').val();
      var maxNum  = $(this).closest('li').data('max_num');
      currNum--;
      if (currNum < 1) currNum = 1;
      if (currNum > maxNum) currNum = maxNum;
      $(this).closest('li').find('.js_numberInp').val(currNum);
      $(this).closest('li').data('curr_num', currNum);
    });
    $('.js_addNum').on('click', function(){
      var currNum = $(this).closest('li').find('.js_numberInp').val();
      var maxNum  = $(this).closest('li').data('max_num');
      currNum++;
      if (currNum < 1) currNum = 1;
      if (currNum > maxNum) {
        currNum = maxNum;
        showMsg('最大数量为'+maxNum);
      }
      $(this).closest('li').find('.js_numberInp').val(currNum);
      $(this).closest('li').data('curr_num', currNum);
    });
    $('.js_numberInp').on('blur', function(){
      var currNum = $(this).val();
      var maxNum  = $(this).closest('li').data('max_num');
      if (currNum > maxNum) {
        currNum = maxNum;
        showMsg('最大数量为'+maxNum);
      }
      $(this).val(currNum);
      $(this).closest('li').data('curr_num', currNum);
    });

    // 同意条款
    $('.js_agreePolicy').click(function(){
      var checked = $(this).data('checked');
      if (checked == 'checked') {
        $(this).find('.ico').remove();
        $(this).data('checked', '');
      } else {
        $(this).data('checked', 'checked');
        $(this).find('input').before('<em class="ico"></em>');
      }
      return false;
    });

    // 提交退货/退款
    $('.js_submitServiceBtn').on('click', function(){
      var ids  = getIds();
      var nums = getNumber();
      var type = $('.js_sltService').attr('data-service_type');
      var isAgree = $('.js_agreePolicy').data('checked');
      var href = $('#serviceForm').attr('action');
      $('.js_relationIds').val(ids.join(','));
      $('.js_serverTypeInp').val(type);
      $('.js_serviceNumbers').val(nums.join(','));

      if (ids.length == 0) {
        showMsg('请选择需要服务的商品');
        return;
      }

      if (type == 0) {
        showMsg('请选择服务类型');
        return;
      }

      if ($('.js_serviceRemarks textarea').val() == '') {
        showMsg('请输入这些商品存在问题，或者需要售后服务的理由');
        return;
      }

      if (isAgree != 'checked') {
        showMsg('请阅读并同意《售后服务》条款');
        return;
      }

      var data = $('#serviceForm').serialize();

      $.post(href, data, function(json){
        if (json.info == 'ok') {
          $('.js_serviceAlert').show().prev().show();
          $('.js_serviceProgress').attr('data-href', siteUrl+'/service/'+json.id);
        } else {
          showMsg(json.info);
        }
      }, 'json');
    });
  });

// 是合格的文件名
  function isAllowFile(fileName, allowType)
  {
    var fileExt = getFileExt(fileName).toLowerCase();
    if (!allowType) {
      allowType = ['jpg', 'jpeg', 'png', 'gif'];
    }

    if ($.inArray(fileExt, allowType) != -1) {
      return true;
    }

    return false;
  }

  function viewImage(file)
  {
    if (typeof FileReader == "undefined") {
      return false;
    }

    var f = file;

    if (!isAllowFile(f.name)) {
      showMsg("请上传常规格式的图片,如：jpg, png等");
      return false;
    }

    var reader = new FileReader();
    reader.onload = (function(theFile){
      return function (e) {
        var tmpSrc = e.target.result;
        if (tmpSrc.lastIndexOf('data:base64') != -1) {
          tmpSrc = tmpSrc.replace('data:base64', 'data:image/jpeg;base64');
        } else if (tmpSrc.lastIndexOf('data:,') != -1) {
          tmpSrc = tmpSrc.replace('data:,', 'data:image/jpeg;base64,');
        }

        var img = '<img src="' + tmpSrc + '" />';
        if ($('div[data-name="'+ f.name +'"]').length > 0) {
          $('div[data-name="'+ f.name +'"]').remove();
        }
        $('.js_imageInput').before('<div data-name="'+ f.name+'" class="image-chunk"><div class="close js_deleteImg"></div>'+img+'<div class="progress js_fileProgress" data-size="'+ f.size +'"></div></div>');
      };
    })(f)
    reader.readAsDataURL(f);
  }

  function getIds()
  {
    var ids = new Array();
    $('.js_orderGoodsList').find('.back-label').each(function(){
      var id = $(this).data('id');
      ids.push(id);
    });

    return ids;
  }
  function getNumber()
  {
    var nums = new Array();
    var ids  = getIds();
    var idsLen = ids.length;
    for (var i = 0; i < idsLen; i++) {
      $('.js_orderGoodsList').find('.back-label[data-id='+ids[i]+']').each(function(){
        var num = $(this).closest('li').data('curr_num');
        nums.push(num);
      });
    }
    return nums;
  }

  function initForm(type){
    var day = $('.js_orderGoodsList').children('ul').data('day');
    var showInfo,goodsInfo = '';
    if (type == 1) {
      showInfo = '收到商品7天内无理由退货, 请将商品全部退回';
      if (day > 7) {
        goodsInfo = '该商品已经超过7天的退货期';
      }
    } else if (type == 2) {
      showInfo = '收到商品14天内无理由换货';
      if (day > 14) {
        goodsInfo = '该商品已经超过14天的换货期';
      }
    } else {
      showInfo = '收到商品1年内免费维修，部分商品终身免费维修';
      if (day > 365) {
        //goodsInfo = '该商品已经超过1年的免费维修期';
      }
    }
    $('.js_serviceInfo').html(showInfo);
    $('.js_orderGoodsList').find('.js_goodsInfo').each(function(){ $(this).html(goodsInfo) });
    if (goodsInfo != '') {
      $('.js_orderGoodsList').attr('data-disabled', 1);
    } else {
      $('.js_orderGoodsList').attr('data-disabled', '');
    }

    if (goodsInfo.length < 1){
      $('.js_goodsViewNumber').each(function(){
        var goodsNum = $(this).data('max_num');
        if (goodsNum > 0) {
          $(this).show().prev().hide();
        }
      });
    }
    $('.js_serviceRemarks').find('textarea').val('');
    $('.js_orderGoodsList').find('.js_sltGoods').each(function(){
      var currSpan   = $(this).children('span');
      currSpan.addClass('back-check');
      currSpan.removeClass('back-label');
      currSpan.css({ marginRight:'10px' });
    });
  }
})()